package com.SouthernWall_404.AgeDust.Common.Network.S2C;

import com.SouthernWall_404.AgeDust.Common.API.Capability.PlayerPersonality;
import com.SouthernWall_404.AgeDust.Common.API.Capability.PlayerPersonalityProvider;
import com.SouthernWall_404.AgeDust.Common.API.Info.AttributesInfo;
import com.SouthernWall_404.AgeDust.Common.API.Info.CharacterInfo;
import com.SouthernWall_404.AgeDust.Common.API.Util.NBTHandler;
import com.SouthernWall_404.AgeDust.Common.Network.ClientHandler.CharacterClientHandler;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

public class CharacterScreenServerPacket {

    public PlayerPersonality playerPersonality;
    public CharacterInfo characterInfo;
    public AttributesInfo attributesInfo;
    public CompoundTag modPack=new CompoundTag();
    public CharacterScreenServerPacket(Player player)
    {
        if(player.getCapability(PlayerPersonalityProvider.PLAYER_PERSONALITY_CAPABILITY).isPresent())
        {
            this.playerPersonality=player.getCapability(PlayerPersonalityProvider.PLAYER_PERSONALITY_CAPABILITY).orElse(null);
        }
        else
        {
            this.playerPersonality=new PlayerPersonality();
        }
        modPack=NBTHandler.createModPack(this.playerPersonality.characterInfo,this.playerPersonality.attributesInfo);

    }
    public CharacterScreenServerPacket(FriendlyByteBuf buf)
    {
        this.modPack=buf.readNbt();
        this.characterInfo=NBTHandler.loadCharacterFromModPack(this.modPack);
        this.attributesInfo=NBTHandler.loadAttributeFromModPack(this.modPack);

    }

    public void encode(FriendlyByteBuf buf)
    {
        buf.writeNbt(this.modPack);

    }
    public void handle(Supplier<NetworkEvent.Context> ctx)
    {
        ctx.get().enqueueWork(() ->
                // 确保其仅在物理客户端上执行
                DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> CharacterClientHandler.handleOpenPacket(this,ctx))
        );
        ctx.get().setPacketHandled(true);
    }
}
